namespace EyeOpen.Dependency
{
	using System;
	using System.Collections.Generic;

	public class DependencyResolver 
		: IDependencyResolver
	{
		private readonly IDependencyRegister dependencyRegister;

		private readonly IDictionary<Type, object> typeDictionary =
			new Dictionary<Type, object>();

		public DependencyResolver(IDependencyRegister dependencyRegister)
		{
			this.dependencyRegister = dependencyRegister;
		}

		public void Register<T>(T obj)
		{
			typeDictionary.Add(typeof(T), obj);
		}

		public T Resolve<T>()
		{
			var type = typeof(T);

			if (typeDictionary.ContainsKey(type))
			{
				return (T)typeDictionary[type];
			}

			var obj = dependencyRegister.GetInstanceOrDefault(type);

			if (EqualityComparer<T>.Default.Equals((T)obj, default(T)))
			{
				throw new ArgumentException(string.Format("Cannot find an implementation for the type \"{0}\".", type.FullName));
			}

			typeDictionary.Add(type, obj);

			return (T)typeDictionary[type];
		}
	}
}